package com.test;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.Random;

public class BaiduPost {

    public static void main(String[] args) {
        int i = 0;
        while (true) {
            try {
                i = i + 1;
                System.out.println("第" + i + "次请求");
                Thread.sleep(1000);
                test();
            } catch (Exception e) {
            }
        }
    }


    public static void test() {
        //指定浏览器驱动路径
        String chromePath = "D://chromedriver//chromedriver.exe";
        //设置指定键对值的系统属性
        System.setProperty("webdriver.chrome.driver", chromePath);
        //创建驱动对象
        WebDriver driver = new ChromeDriver();

        try {
            //获取网址
            driver.get("https://www.baidu.com");

            //线程睡眠3秒（目的是等待浏览器打开完成）

//            Thread.sleep(3000);

            //获取百度搜索输入框元素，并自动写入搜索内容

//        driver.findElement(By.id("kw")).sendKeys("selenium");

//        driver.findElement(By.id("kw")).sendKeys("selenium");

//        driver.find_element_by_css_selector('div>h3>a').click()

            Random random = new Random();
            int a = random.nextInt(5);
            for (int i = 0; i <= a; i++) {
                driver.findElement(By.id("hotsearch-refresh-btn")).click();
                Thread.sleep(500);
            }

            driver.findElement(By.cssSelector("div>ul>li>a")).click();
            //线程睡眠1秒
            Thread.sleep(3000);

            //获取“百度一下”元素，并自动点击

//        driver.findElement(By.id("su")).click();

            //退出浏览器
            driver.quit();
        } catch (Exception e) {
            System.out.println("异常退出");
            //退出浏览器
            driver.quit();
        }

    }
}